import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import '../../../common/utils/image_picker_util.dart';

/// 图片缓存工具类
/// 统一处理聊天界面中的图片尺寸获取和缓存
class ImageCacheUtils {
  // 单例模式
  static final ImageCacheUtils _instance = ImageCacheUtils._internal();
  factory ImageCacheUtils() => _instance;
  ImageCacheUtils._internal();

  // 图片尺寸缓存
  final Map<String, Size> _imageSizeCache = {};

  // 图片路径缓存，避免重复的文件路径解析
  final Map<String, String?> _imagePathCache = {};

  /// 获取缓存的图片尺寸
  Size? getCachedImageSize(String imageUrl) {
    return _imageSizeCache[imageUrl];
  }

  /// 检查是否有缓存
  bool hasCachedSize(String imageUrl) {
    return _imageSizeCache.containsKey(imageUrl);
  }

  /// 获取缓存的图片路径
  String? getCachedImagePath(String relativePath) {
    return _imagePathCache[relativePath];
  }

  /// 缓存图片路径
  void cacheImagePath(String relativePath, String? fullPath) {
    _imagePathCache[relativePath] = fullPath;
  }

  /// 获取图片完整路径（带缓存）
  Future<String?> getFullImagePath(String relativePath) async {
    // 检查路径缓存
    if (_imagePathCache.containsKey(relativePath)) {
      return _imagePathCache[relativePath];
    }

    // 获取完整路径并缓存
    final fullPath = await ImagePickerUtil.getFullImagePath(relativePath);
    _imagePathCache[relativePath] = fullPath;
    return fullPath;
  }

  /// 获取图片尺寸（带缓存）
  Future<Size> getImageSize(String imageUrl) async {
    // 检查缓存
    if (_imageSizeCache.containsKey(imageUrl)) {
      return _imageSizeCache[imageUrl]!;
    }

    final Completer<Size> completer = Completer<Size>();
    late ImageStreamListener listener;
    late ImageStream stream;

    try {
      // 判断是否是本地文件路径（相对路径）
      if (!imageUrl.startsWith('assets/') && !imageUrl.startsWith('/')) {
        // 使用缓存的路径获取方法
        final fullPath = await getFullImagePath(imageUrl);
        if (fullPath != null && File(fullPath).existsSync()) {
          stream = FileImage(File(fullPath)).resolve(ImageConfiguration.empty);
        } else {
          // 文件不存在，返回默认尺寸
          const defaultSize = Size(150, 150);
          _imageSizeCache[imageUrl] = defaultSize;
          return defaultSize;
        }
      } else {
        // Assets图片
        stream = AssetImage(imageUrl).resolve(ImageConfiguration.empty);
      }

      listener = ImageStreamListener(
        (ImageInfo info, bool synchronousCall) {
          final image = info.image;
          final size = Size(image.width.toDouble(), image.height.toDouble());

          // 缓存结果
          _imageSizeCache[imageUrl] = size;

          completer.complete(size);
          stream.removeListener(listener);
        },
        onError: (exception, stackTrace) {
          // 出错时返回默认尺寸
          const defaultSize = Size(150, 150);
          _imageSizeCache[imageUrl] = defaultSize;
          completer.complete(defaultSize);
          stream.removeListener(listener);
        },
      );

      stream.addListener(listener);
    } catch (e) {
      // 异常时返回默认尺寸
      const defaultSize = Size(150, 150);
      _imageSizeCache[imageUrl] = defaultSize;
      completer.complete(defaultSize);
    }

    return completer.future;
  }

  /// 预加载图片尺寸列表
  Future<void> preloadImageSizes(List<String> imageUrls) async {
    final futures = imageUrls
        .where((url) => !_imageSizeCache.containsKey(url))
        .map(
          (url) => getImageSize(url).catchError((error) {
            // 忽略单个图片加载错误，不影响其他图片
            return const Size(150, 150); // 返回默认尺寸
          }),
        );

    await Future.wait(futures);
  }

  /// 清除缓存
  void clearCache() {
    _imageSizeCache.clear();
    _imagePathCache.clear();
  }

  /// 清除特定图片的缓存
  void removeCachedSize(String imageUrl) {
    _imageSizeCache.remove(imageUrl);
    _imagePathCache.remove(imageUrl);
  }

  /// 获取缓存大小
  int get cacheSize => _imageSizeCache.length;

  /// 获取所有缓存的图片URL
  List<String> get cachedImageUrls => _imageSizeCache.keys.toList();
}
